import {uSelectHistoryDataByQueryVo} from '@/api/liveDataShow'
import useDeviceHook from '@/hooks/device'
import useLoading from '@/hooks/loading'
import {useInterval, useTimeOut} from '@/hooks/time'
import {imagesUrl} from '@/libs/baseUrl'
import deepClone from '@/libs/deepClone'
import cecharts, {ECOption} from '@/libs/global/echarts'
import {str2num} from '@/libs/toolkit'
import dayjs, {Dayjs} from 'dayjs'
import {PropType} from 'vue'
import CEcharts from '../echarts'
import {CImage, IconImg, LiveDataParamOfIcon, ParamIcon, ParamOfIcon, ParamOfStatus} from '../image'
import RollerDigital from '../rollerDigital'
import {CnMediumSpan, CnNormalSpan} from '../text'
import WaterTarget from '../waterTarget'
import {DateTimeRange} from './dateTime'

const TableCellText = defineComponent({
  setup(props, {slots}) {
    return () => <CnMediumSpan class='text-20 text-white'>{slots.default?.()}</CnMediumSpan>
  }
})

const ParamTableCell = defineComponent({
  props: {
    isOdd: Boolean,
    isBorderReversal: Boolean,
    isBorderLinear: {
      type: Boolean,
      default: true
    }
  },
  setup(props, {slots}) {
    return () => (
      <div
        class='h-80 leading-80 px-12'
        style={{
          borderBottom: '1px solid',
          borderImage: props.isBorderLinear
            ? props.isBorderReversal
              ? 'linear-gradient(to right, #032b58 ,  #035988) 1'
              : 'linear-gradient(to right, #035988 ,  #032b58) 1'
            : '',
          borderColor: props.isBorderLinear ? '' : '#035988',

          background: props.isOdd ? 'rgba(0,125,187,0.2)' : ' rgba(0,125,187,0.15)',
          textAlign: 'center'
        }}
      >
        {slots.default?.()}
      </div>
    )
  }
})

/**参数表格 */
const ParamTable = defineComponent({
  props: {
    paramList: {
      type: Array as PropType<LiveData.DevLiveDataParam[]>,
      required: true
    }
  },
  setup(props, ctx) {
    const {startInterval} = useInterval()
    const paramList = ref<LiveData.DevLiveDataParam[]>([])

    watch(
      () => props.paramList,
      (n, o) => {
        if (n) {
          paramList.value = deepClone(n)
        }
        if (o?.length === 0 && n.length > 5) {
          startInterval(() => {
            if (paramList.value.length) {
              const firstParam = paramList.value[0]
              paramList.value.splice(0, 1)
              paramList.value.push(firstParam)
            }
          }, 1.5 * 1000)
        }
      },
      {immediate: true}
    )

    onMounted(() => {
      // paramList.value.length > 5 &&
      //   startInterval(() => {
      //     if (paramList.value.length) {
      //       let firstParam = paramList.value[0]
      //       paramList.value.splice(0, 1)
      //       paramList.value.push(firstParam)
      //     }
      //   }, 1.5 * 1000)
    })

    return () => (
      <div
        id='scrollBox'
        class='w-full rounded-10 overflow-hidden'
        style={{
          // backgroundImage: `url(${imagesUrl('bg-liveDataShowWaterAnalyze')})`,
          // backgroundSize: '100% 100%',
          // backgroundRepeat: 'no-repeat'
          borderImage: 'linear-gradient(322deg, rgba(5, 219, 251, 1), rgba(5, 219, 251, 0))',
          borderImageSlice: '11px',
          background: 'rgba(0,125,187,0.2)'
        }}
      >
        <div class='grid grid-cols-10 border-1 scrollShow-to-bottom'>
          {/* 参数图标 */}
          <div>
            {paramList.value.map((param, index) => (
              <ParamTableCell
                class='flex justify-end items-center'
                isBorderReversal={true}
                isOdd={index % 2 !== 0}
              >
                <ParamIcon imgName={'liveData-' + param.paramName}></ParamIcon>
              </ParamTableCell>
            ))}
          </div>
          {/* 名称 */}
          <div>
            {paramList.value.map((param, index) => (
              <ParamTableCell class='text-left' isOdd={index % 2 !== 0}>
                <TableCellText>{param.paramName}</TableCellText>
              </ParamTableCell>
            ))}
          </div>
          {/* 时间 */}
          <div class='col-span-2'>
            {paramList.value.map((param, index) => (
              <ParamTableCell isBorderReversal={true} isOdd={index % 2 !== 0}>
                <TableCellText>{param.checkTime}</TableCellText>
              </ParamTableCell>
            ))}
          </div>
          {/* 状态 */}
          <div class='col-span-2'>
            {paramList.value.map((param, index) => (
              <ParamTableCell isBorderLinear={false} isOdd={index % 2 !== 0}>
                <ParamOfStatus
                  status={param.paramStatusCode}
                  statusStyle={{width: '12px', height: '12px'}}
                >
                  <TableCellText>{param.paramStatus}</TableCellText>
                </ParamOfStatus>
              </ParamTableCell>
            ))}
          </div>
          {/* 数值 */}
          <div class='col-span-2'>
            {paramList.value.map((param, index) => {
              const val = str2num(param.paramValue || '')
              return val !== undefined ? (
                <ParamTableCell isOdd={index % 2 !== 0}>
                  <RollerDigital
                    class='text-20 text-white'
                    endVal={val}
                    decimals={2}
                  ></RollerDigital>
                  <TableCellText class='ml-12'>{param.paramUnit}</TableCellText>
                </ParamTableCell>
              ) : (
                <TableCellText class='ml-12'>---</TableCellText>
              )
            })}
          </div>
          {/* 合格标准 */}
          <div class='col-span-2'>
            {paramList.value.map((param, index) => (
              <ParamTableCell isBorderReversal={true} isOdd={index % 2 !== 0}>
                <TableCellText>{param.standRange || '---'}</TableCellText>
              </ParamTableCell>
            ))}
          </div>
        </div>
      </div>
    )
  }
})
const ParamEchart = defineComponent({
  props: {
    isFullScreen: {
      type: Boolean,
      required: true
    },
    dev: {
      type: Object as PropType<SimpleDeviceData>,
      required: true
    }
  },
  setup(props, ctx) {
    const {startInterval} = useInterval()
    const {startTimeout, closeTimeout} = useTimeOut()

    let ec: cecharts.ECharts | undefined = undefined

    const dateTimes = ref<[Dayjs, Dayjs]>([dayjs(), dayjs()])

    function getDataSource() {
      ec?.showLoading()

      uSelectHistoryDataByQueryVo({
        devId: props.dev.devId,
        startTime: dateTimes.value[0].format('YYYY-MM-DD 00:00:00'),
        endTime: dateTimes.value[1].format('YYYY-MM-DD 23:59:59')
      })
        .then(res => {
          const option: ECOption = {
            legend: {
              textStyle: {
                color: '#fff'
              }
            },
            tooltip: {
              trigger: 'axis',
              order: 'valueDesc',
              className: 'default-tooltipBox'
            },
            grid: {
              left: '6%',
              right: '6%',
              top: '10%',
              bottom: '8%'
            },
            dataZoom: {
              type: 'inside',
              start: 0,
              end: 100,
              disabled: false
            },
            xAxis: {
              type: 'category',
              nameLocation: 'middle',
              axisLabel: {
                color: '#fff'
              }
            },
            yAxis: {
              type: 'value',
              axisLabel: {
                fontSize: '12px',
                color: '#fff'
              }
            },
            animation: true,
            animationDuration: 3000,
            series: []
          }

          const seriesList: any[] = []
          for (const key in res.data) {
            const arrayVal = res.data[key]

            const seriesData = arrayVal
              .map(item => [
                item.checkTime,
                item.checkDataValue,
                {
                  name: item.checkDataName,
                  value: item.checkDataValue,
                  status: item.paramStatus,
                  time: item.checkTime
                }
              ])
              .sort((a, b) => dayjs(a[0] as string).unix() - dayjs(b[0] as string).unix())

            seriesList.push({
              type: 'line',
              showSymbol: false,
              name: key,
              endLabel: {
                show: true,
                formatter: function (params: any) {
                  const lastVal = arrayVal.slice(-1)[0]
                  return key + ': ' + lastVal.checkDataValue
                }
              },
              labelLayout: {
                moveOverlap: 'shiftY'
              },
              emphasis: {
                focus: 'series'
              },
              lineStyle: {
                width: 4
              },
              data: key === 'pH(1)' ? [] : seriesData
            })
          }

          option.series = seriesList

          console.log(ec, option)

          ec?.setOption(option)
          ec?.hideLoading()
        })
        .catch(err => {
          ec?.hideLoading()
        })
    }

    watch(
      () => props.isFullScreen,
      n => {
        nextTick(() => {
          ec && ec.resize()
        })
      }
    )

    watch(
      () => dateTimes.value,
      n => {
        startInterval(
          () => {
            getDataSource()
          },
          5 * 60 * 1000,
          false
        )
      }
    )

    onMounted(() => {})

    return () => (
      <div class=''>
        <div class='w-full h-30 mb-10'>
          <DateTimeRange
            class='float-right'
            v-model={[dateTimes.value, 'dateTimes']}
            dateTabTextColor='white'
          ></DateTimeRange>
        </div>
        <div class={['w-full', props.isFullScreen ? 'h-510' : 'h-400']}>
          <CEcharts
            id={'waterAnalyze-lineEchart' + props.dev.devId}
            width={'100%'}
            height={'100%'}
            lazy={true}
            onInitEc={echart => {
              ec = echart
            }}
          ></CEcharts>
        </div>
      </div>
    )
  }
})

/**设备数据 */
const DevLiveData = defineComponent({
  props: {
    dev: {type: Object as PropType<SimpleDeviceData>, required: true},
    current: {type: Number, required: true},
    updateTargets: {
      type: Array as unknown as PropType<[number, number] | [number]>,
      required: true
    },
    isFullScreen: {
      type: Boolean,
      required: true
    }
  },
  setup(props, ctx) {
    const {updateLiveData, liveData} = useDeviceHook()
    const {loading, startLoading, closeLoading} = useLoading()
    const {startInterval, closeInterval} = useInterval()

    startInterval(updateDataSource, 5 * 60 * 1000, false)
    function updateDataSource() {
      startLoading()
      updateLiveData({
        devId: props.dev.devId,
        updateDataSource: true,
        success(data) {
          closeLoading()
        }
      })
    }

    const dataShowType = ref<'table' | 'echart'>('table')

    return () => (
      <div class='w-full h-full overflow-hidden flex flex-col'>
        <div
          class='w-full h-58 pl-30 flex items-center mb-29'
          style={{
            backgroundImage: `url(${imagesUrl('bg-liveDataShowTitle')})`,
            backgroundSize: '100% 100%',
            backgroundRepeat: 'no-repeat'
          }}
        >
          <IconImg imgName='liveDataShowDev' class='w-32 h-32 '></IconImg>
          <CnNormalSpan
            class='text-white text-32 px-4'
            style={{
              fontFamily: 'liveDataShow-devName',
              background: 'linear-gradient(180deg, #FFFFFF 0%, #06B7FF 100%)',
              '-webkit-background-clip': 'text',
              '-webkit-text-fill-color': 'transparent'
            }}
          >
            {props.dev.isManage === '是' ? '我的设备' : '我的设备'}
          </CnNormalSpan>
        </div>
        <div
          class='w-full h-160 py-28 px-40 flex items-center gap-x-24 mb-38 relative'
          style={{
            backgroundImage: `url(${imagesUrl('bg-liveDataShowWaterAnalyze')})`,
            backgroundSize: '100% 100%',
            backgroundRepeat: 'no-repeat'
          }}
        >
          <WaterTarget
            id={
              'liveDataShow-' + liveData.value?.devId + '-' + `${Math.random() * 10000}`.slice(0, 4)
            }
            radius={52}
            range={((liveData.value?.nowStandRatio || 0) / 100) * 360}
            // borderColor={ratio2color(parseInt(`${60}` || '0'))}
            borderColor={['#00F0FF', '#00A4FF']}
            tooltipTitle={'水质评分'}
            borderWidth={10}
            scaleColor={'#79EEFF'}
          >
            <RollerDigital
              class='text-34'
              endVal={liveData.value?.nowStandRatio || 0}
              bold={true}
              style={{
                background: 'linear-gradient(180deg, #00F0FF 0%, #00A4FF 100%)',
                '-webkit-background-clip': ' text',
                '-webkit-text-fill-color': 'transparent'
              }}
            ></RollerDigital>
          </WaterTarget>

          <div class=''>
            <div class='mb-15 flex items-center gap-x-29'>
              <CnMediumSpan class='text-white text-24'>{liveData.value?.devName}</CnMediumSpan>
              <CnMediumSpan class='text-white text-24'>{liveData.value?.checkResult}</CnMediumSpan>
            </div>
            <div class='flex items-center gap-x-16'>
              {liveData.value?.paramList.map(param => (
                <ParamOfStatus status={param.paramStatusCode}>
                  <span class='text-white text-16'>{param.paramName}</span>
                </ParamOfStatus>
              ))}
            </div>
          </div>

          <CImage
            imgName='liveDataShow-lineEcahrt-bg'
            class={[
              'w-200 h-full absolute right-0 top-0 cursor-pointer opacity-80',
              dataShowType.value === 'echart' ? 'hidden' : ''
            ]}
            onClick={() => {
              dataShowType.value = 'echart'
            }}
            title='点击切换显示历史曲线图表'
          ></CImage>

          <CImage
            imgName='liveDataShow-table-bg'
            class={[
              'w-200 h-full absolute right-0 top-0 cursor-pointer opacity-80 p-20',
              dataShowType.value === 'table' ? 'hidden' : ''
            ]}
            onClick={() => {
              dataShowType.value = 'table'
            }}
            title='点击切换显示实时数据'
          ></CImage>
        </div>

        {dataShowType.value === 'echart' ? (
          <ParamEchart dev={props.dev} isFullScreen={props.isFullScreen}></ParamEchart>
        ) : (
          <ParamTable
            class={['w-full h-auto', props.isFullScreen ? 'max-h-560' : 'max-h-400']}
            paramList={liveData.value?.paramList ? liveData.value.paramList : []}
          ></ParamTable>
        )}
      </div>
    )
  }
})

/**大屏展示组件 可全屏 */
const LiveDataShowScreen = defineComponent({
  props: {
    visible: Boolean,
    devs: Array as PropType<SimpleDeviceData[]>,
    /**1开启手动切换 2开启自动播放 */
    showType: Number as PropType<1 | 2>
  },
  emits: {
    close: (): boolean => true,
    fullScreen: (data: boolean): boolean => true
  },
  setup(props, {emit}) {
    const isFullScreen = ref(false)
    function openFullScreen() {
      isFullScreen.value = true
      emit('fullScreen', true)
    }
    function closeFullScreen() {
      isFullScreen.value = false
      emit('fullScreen', false)
    }

    const slideRef = ref()
    const currentSlide = ref(0)
    function handleBeforeChange(currentIndex: any, fromIndex: any) {
      console.log(currentIndex, fromIndex)
      currentSlide.value = currentIndex
    }

    onMounted(() => {
      console.log(slideRef.value)
    })
    return () =>
      props.visible ? (
        <div
          class={[
            'fixed top-0 left-0 w-screen h-screen px-40 py-24 ',
            props.visible ? 'page-show-left' : 'hidden'
          ]}
          style={{
            background: 'rgba(0,0,0,0.5)'
          }}
        >
          <div class='w-full h-40 flex justify-between items-center mb-16'>
            <i
              class='iconfont icon-fanhui1 text-white text-40 cursor-pointer'
              onClick={() => emit('close')}
            ></i>
            <i
              class='iconfont icon-quanping1 text-white text-40 cursor-pointer'
              onClick={openFullScreen}
            ></i>
          </div>

          <div
            class={[
              'pt-60 flex flex-col',
              isFullScreen.value ? 'fixed top-0 left-0 w-screen' : 'rounded-15 '
            ]}
            style={{
              backgroundImage: `url(${imagesUrl('bg-liveDataShow')})`,
              backgroundSize: '100% 100%',
              backgroundRepeat: 'no-repeat',
              height: isFullScreen.value ? '100vh' : 'calc(100% - 40px)'
            }}
          >
            {isFullScreen.value ? (
              <div class='absolute top-20 left-0 w-full h-40 mb-20 px-10 leading-40 text-right overflow-hidden'>
                <i
                  class='h-40 iconfont icon-fullscreen-exit text-white text-40 cursor-pointer '
                  onClick={closeFullScreen}
                ></i>
              </div>
            ) : null}

            {/* 实时数据展示区 */}
            {/* 轮播盒子 */}
            <el-carousel
              class={['min-w-1764 px-38 pb-40 CBC-carousel h-full']}
              ref={slideRef}
              autoplay={props.showType === 2}
              easing='linear'
              interval={5000}
              onChange={handleBeforeChange}
              // afterChange={handleAfterChange}
              arrow={props.devs && props.devs.length > 1 ? 'hover' : 'never'}
            >
              {props.visible &&
                props.devs &&
                props.devs.length &&
                props.devs.map((dev, index) => (
                  <el-carousel-item>
                    <DevLiveData
                      dev={dev}
                      updateTargets={[index]}
                      current={currentSlide.value}
                      isFullScreen={isFullScreen.value}
                    ></DevLiveData>
                  </el-carousel-item>
                ))}
            </el-carousel>
          </div>
        </div>
      ) : null
  }
})

export default LiveDataShowScreen
